﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module.QuanLyKhachHang;

namespace HeThongSpa.QuanLyKhachHang.KhachHang
{
    public partial class DanhSachKhachHang : Page
    {
        private const int PageSize = 20;

        private DanhMucKhachHang _danhMucKhachHang = new DanhMucKhachHang();

        private int _totalrow;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                txtTuNgay.Text = DateTime.Now.ToString("dd-MM-yyyy");
                txtDenNgay.Text = DateTime.Now.ToString("dd-MM-yyyy");
                LoadPage();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["CheckRefresh"] = Session["CheckRefresh"];
        }

        private void LoadPage()
        {
            _danhMucKhachHang = new DanhMucKhachHang();
            if (hfTimKiem.Value.Equals("true"))
            {
                _danhMucKhachHang.MaKhachHang = txtTuKhoa.Text.Trim();
                _danhMucKhachHang.HoTen = txtTuKhoa.Text.Trim();
            }
            if (string.IsNullOrEmpty(txtTuNgay.Text.Trim()) || string.IsNullOrEmpty(txtDenNgay.Text.Trim()))
            {
                txtTuNgay.Text = DateTime.Now.ToString("dd-MM-yyyy");
                txtDenNgay.Text = DateTime.Now.ToString("dd-MM-yyyy");
            }
            gvDanhMuc.DataSource = _danhMucKhachHang.SelectAll(_danhMucKhachHang,
                Convert.ToDateTime(DateTime.ParseExact(txtTuNgay.Text.Trim(), "dd-MM-yyyy", null).ToString("yyyy-MM-dd")),
                Convert.ToDateTime(DateTime.ParseExact(txtDenNgay.Text.Trim(), "dd-MM-yyyy", null).ToString("yyyy-MM-dd")),
                Convert.ToInt32(hfPageIndex.Value.Trim()), PageSize, out _totalrow);
            gvDanhMuc.DataBind();
            GeneratePager(_totalrow, PageSize, Convert.ToInt32(hfPageIndex.Value.Trim()));
            Session["CheckRefresh"] = Server.UrlEncode(DateTime.Now.ToString(CultureInfo.InvariantCulture));
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
                {
                    _danhMucKhachHang.TaiKhoan = Session["username"].ToString().Trim();
                    _danhMucKhachHang.MaKhachHang = hfMaKhachHang.Value.Trim();
                    _danhMucKhachHang.HoTen = txtHoTen.Text.Trim();
                    _danhMucKhachHang.NgaySinh = Convert.ToDateTime(DateTime.ParseExact(txtNgaySinh.Text.Trim(), "dd-MM-yyyy", null).ToString("yyyy-MM-dd"));
                    _danhMucKhachHang.GioiTinh = Convert.ToBoolean(ddlGioiTinh.SelectedValue.Trim());
                    _danhMucKhachHang.DiaChi = txtDiaChi.Text.Trim();
                    _danhMucKhachHang.DienThoai = txtDienThoai.Text.Trim();
                    _danhMucKhachHang.Email = txtEmail.Text.Trim();
                    _danhMucKhachHang.NgayDen = Convert.ToDateTime(DateTime.ParseExact(txtNgayDen.Text.Trim(), "dd-MM-yyyy", null).ToString("yyyy-MM-dd"));
                    _danhMucKhachHang.HinhAnh = "";
                    if (string.IsNullOrEmpty(_danhMucKhachHang.MaKhachHang))
                    {
                        if (!_danhMucKhachHang.Insert(_danhMucKhachHang))
                            ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                                "bootbox.alert('Cập nhật thất bại, vui lòng thử lại.')", true);
                    }
                    else
                    {
                        if (!_danhMucKhachHang.Update(_danhMucKhachHang))
                            ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                                "bootbox.alert('Cập nhật thất bại, vui lòng thử lại.')", true);
                    }
                }
                ResetPage();
            }
        }

        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            hfMaKhachHang.Value = "";
            hfTimKiem.Value = "true";
            hfPageIndex.Value = "1";
            LoadPage();
        }

        protected void btnNhapLai_Click(object sender, EventArgs e)
        {
            ResetPage();
        }

        protected void btnSua_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                    ResetPage();
                else
                {
                    hfMaKhachHang.Value = ((LinkButton)sender).CommandArgument;
                    var dt = _danhMucKhachHang.SelectByMaKhachHang(hfMaKhachHang.Value.Trim());
                    if (dt.Rows.Count <= 0) return;
                    txtHoTen.Text = dt.Rows[0]["HoTen"].ToString().Trim();
                    txtNgaySinh.Text = Convert.ToDateTime(dt.Rows[0]["NgaySinh"].ToString().Trim()).ToString("dd-MM-yyyy");
                    ddlGioiTinh.SelectedValue = dt.Rows[0]["GioiTinh"].ToString().Trim();
                    txtDienThoai.Text = dt.Rows[0]["DienThoai"].ToString().Trim();
                    txtDiaChi.Text = dt.Rows[0]["DiaChi"].ToString().Trim();
                    txtEmail.Text = dt.Rows[0]["Email"].ToString().Trim();
                    txtNgayDen.Text = Convert.ToDateTime(dt.Rows[0]["NgayDen"].ToString().Trim()).ToString("dd-MM-yyyy");
                    ClientScript.RegisterClientScriptBlock(typeof(string), "alert", "$(function(){$('#thongtinkhachang').removeClass('collapsed-box'); $('#thongtinkhachang .box-header i').removeClass('fa-plus').addClass('fa-minus'); $('#" + txtHoTen.ClientID + "').focus();});", true);
                }
            }
        }

        protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "PageNo") return;
            hfPageIndex.Value = e.CommandArgument.ToString();
            LoadPage();
            e.Item.Attributes.Add("disabled", "disabled");
        }

        public void GeneratePager(int totalRowCount, int pageSize, int currentPage)
        {
            const int totalLinkInPage = 4;
            var totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

            var startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
            var lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

            if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
            {
                lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
                startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
            }

            var pageLinkContainer = new List<ListItem>();

            if (startPageLink != 1)
            {
                pageLinkContainer.Add(new ListItem("«", "1", currentPage != 1));
            }
            for (var i = startPageLink; i <= lastPageLink; i++)
            {
                pageLinkContainer.Add(new ListItem(i.ToString(CultureInfo.InvariantCulture),
                    i.ToString(CultureInfo.InvariantCulture), currentPage != i));
            }
            if (lastPageLink != totalPageCount)
                pageLinkContainer.Add(new ListItem("»", totalPageCount.ToString(CultureInfo.InvariantCulture),
                    currentPage != totalPageCount));

            dlPager.DataSource = pageLinkContainer;
            dlPager.DataBind();
        }

        private void ResetPage()
        {
            hfMaKhachHang.Value = string.Empty;
            txtHoTen.Text = string.Empty;
            txtNgaySinh.Text = DateTime.Now.ToString("dd-MM-yyyy");
            ddlGioiTinh.SelectedIndex = 0;
            txtDienThoai.Text = string.Empty;
            txtDiaChi.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtNgayDen.Text = DateTime.Now.ToString("dd-MM-yyyy");
            hfTimKiem.Value = "false";
            hfPageIndex.Value = "1";
            LoadPage();
        }
    }
}